package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.FormColumn;
import com.ruoyi.system.service.IFormColumnService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.FormData;
import com.ruoyi.system.service.IFormDataService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 单内容Controller
 *
 * @author ruoyi
 * @date 2023-11-16
 */
@RestController
@RequestMapping("/system/data")
public class FormDataController extends BaseController
{
    @Autowired
    private IFormDataService formDataService;

    @Autowired
    private IFormColumnService formColumnService;

    /**
     * 查询单内容列表
     */
    @PreAuthorize("@ss.hasPermi('system:data:list')")
    @GetMapping("/list")
    public TableDataInfo list(FormData formData)
    {
        startPage();
        LambdaQueryWrapper<FormData> lambdaQueryWrapper =new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(FormData::getFormId,formData.getFormId());
       if(formData.getSearchForm()!=null) {
          List<String> listStr =new ArrayList<>();
          Set<String> keySet = formData.getSearchForm().keySet();
          for(String k:keySet){
              if(StringUtils.isNotEmpty(formData.getSearchForm().getString(k))){
                  String s =  " JSON_EXTRACT( form_data, '$."+k+"' ) ='"+formData.getSearchForm().getString(k)+"' ";
                  listStr.add(s);
              }

          }
           String strSql =listStr.stream().collect(Collectors.joining(" and "));

          if(StringUtils.isNotEmpty(strSql)){
              lambdaQueryWrapper.apply(strSql);
          }

       }


        lambdaQueryWrapper.orderByDesc(FormData::getCreateTime);
        List<FormData> list = formDataService.list(lambdaQueryWrapper);
        //List<FormColumn> columnList =  formColumnService.listColumnList(formData.getFormId());
        List<JSONObject> dataList = new ArrayList<>();
        list.forEach(it->{
            JSONObject jo =   it.getFormData();
            jo.put("id",it.getId());
            dataList.add(jo);
        });
        TableDataInfo tableDataInfo =getDataTable(list);
        tableDataInfo.setRows(dataList);
        return tableDataInfo;
    }



    /**
     * 导出单内容列表
     */
    @PreAuthorize("@ss.hasPermi('system:data:export')")
    @Log(title = "单内容", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FormData formData)
    {
        List<FormData> list = formDataService.list();
        ExcelUtil<FormData> util = new ExcelUtil<FormData>(FormData.class);
        util.exportExcel(response, list, "单内容数据");
    }

    /**
     * 获取单内容详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:data:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(formDataService.getById(id));
    }

    /**
     * 新增单内容
     */
    @PreAuthorize("@ss.hasPermi('system:data:add')")
    @Log(title = "单内容", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FormData formData)
    {
        return toAjax(formDataService.save(formData));
    }

    /**
     * 修改单内容
     */
    @PreAuthorize("@ss.hasPermi('system:data:edit')")
    @Log(title = "单内容", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FormData formData)
    {
        return toAjax(formDataService.updateById(formData));
    }

    /**
     * 删除单内容
     */
    @PreAuthorize("@ss.hasPermi('system:data:remove')")
    @Log(title = "单内容", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(formDataService.removeByIds(Arrays.asList(ids)));
    }
}
